package com.example.miniomultipartupload.util;

import cn.hutool.core.util.IdUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author
 */
public class FileUploadUtils
{

    /**
     * 编码文件名
     */
    public static final String extractFilename(MultipartFile file)
    {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(IdUtil.fastUUID()), Seq.getId(Seq.uploadSeqType), getExtension(file));
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename(String originFileName)
    {
        return StringUtils.format("{}/{}_{}.{}", DateUtils.datePath(),
                FilenameUtils.getBaseName(IdUtil.fastUUID()), Seq.getId(Seq.uploadSeqType),  FilenameUtils.getExtension(originFileName));
    }


    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension(MultipartFile file)
    {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension))
        {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }
}
